package com.guiji.quartz.domain;

import cn.hutool.core.date.DateUtil;
import cn.hutool.crypto.SecureUtil;
import cn.hutool.http.HttpException;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.json.JSONUtil;
import cn.wanghaomiao.xpath.model.JXDocument;
import com.guiji.common.utils.spring.SpringUtils;
import com.guiji.quartz.service.ISpiderNewsService;
import com.guiji.quartz.service.RedisService;
import com.guiji.quartz.task.DataSaveUtil;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @program: cms-vue-plus
 * @description:
 * @author: gaoX
 * @create: 2021-10-19 14:14
 **/
public class ZhihuRibao {
	private static final Logger log = LoggerFactory.getLogger(ZhihuRibao.class);

	public void mainMethod() throws Exception {
		HttpResponse response = null;
		try {
			response = HttpRequest.get("http://www.zhihudaily.me/1")
				.header("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9")
				.header("Accept-Encoding", "gzip, deflate")
				.setConnectionTimeout(15000)
				.execute();
		} catch (Exception e) {
			log.error("ZhihuRibao代理失败1"+e);
			return;
		}
		String resp = response.body();
		List<String> resUrl = getUrl(resp);
		getContent(resUrl);

	}

	private static void getContent(List<String> listContent) {
		for (String url : listContent) {
			log.info("getContent执行到-{},listContent长度-{}", url, listContent.size());
			String doc = null;
			JXDocument jxDocument = null;
			try {
				HttpResponse response = HttpRequest.get(url).setConnectionTimeout(15000).execute();
				doc = response.body();
				jxDocument = new JXDocument(doc);
			} catch (HttpException e) {
				log.info("代理失败2"+e);
			}
			String title ;
			try {
				title = (String) jxDocument.sel("//p[@class='DailyHeader-title']/text()").get(0);
			} catch (Exception e) {
				log.error("标题错误-------------" + url + "-------------------标题错误");
				continue;
			}
			Document document ;
			String content ;
			try {
				document = Jsoup.parse(doc);
				content = document.getElementsByClass("content").get(0).toString();
				content = content.replaceAll("\n", "\\$\\$\\$").replaceAll("<.*?>"," ");
			} catch (Exception e) {
				continue;
			}

			List<Object> imgs ;
			try {
				imgs = jxDocument.sel("//img[@class='content-image']/@src");
			} catch (Exception e) {
				log.error("获取图片失败");
				continue;
			}

			Date date = new Date();
			List<Object> newImgs = new ArrayList<>();
			for (Object img:imgs) {
				if(!img.toString().contains("gif")){
					newImgs.add(img);
				}
			}


			if (content.length() > 50000 || content.toString().replaceAll("\\$|[\\s\\p{Zs}]","").length() < 20 || newImgs.size() > 20) {
				continue;
			}
			try {
				DataSaveUtil.saveData(title, content.toString(), newImgs, url, date, "http://www.zhihudaily.me/1", "知乎日报");
				log.info(Thread.currentThread().getName() + "-----------------知乎日报----------------");
			} catch (Exception e) {
				continue;
			}
		}
	}

	private static List<String> getUrl(String content) {

		List<String> res = new ArrayList<>();
		String pattern = "http://daily.zhihu.com/story/[0-9]{7}";
		Pattern p = Pattern.compile(pattern);
		Matcher m = p.matcher(content);
		while (m.find()) {
			res.add(m.group());
		}
		return res;
	}

}
